// load the Google data JS Client Library
google.load('gdata', '2.x', {packages: ['calendar' , 'contacts']});

// This is the url for the user's default calendar
var EVENT_FEED_URL =
    'https://www.google.com/calendar/feeds/default/private/full';

// This variable is used for retrieving and adding events
var calendarService;

/**
 * This function checks if the user is logged in, 
 * and changes the login button and displayed sections accordingly.
 * It also initializes the calendarService variable
 * and calls a function to fill in the form based on the URL.
 */
function init() {

  var token = google.accounts.user.checkLogin(EVENT_FEED_URL);

  calendarService = new google.gdata.calendar.CalendarService(
      'sample-birthdayManager');
	  
	  calendarService.useOAuth('google');

  var authButton = document.getElementById('auth_button');

  if (google.accounts.user.checkLogin(EVENT_FEED_URL)) {
    authButton.value = 'Logout';
   
    getEvents();
  } else {
    document.getElementById('loginNotice').style.display = 'block';
    authButton.value = 'Login';
  }
};

// Tells the google JS lib to call the init function once loaded
google.setOnLoadCallback(init);

/**
 * This function is triggered by the login/logout button.
 * If the user is logged in to the app, it logs them out.
 * If the user is logged out to the app, it logs them in.
 */
function loginOrLogout(){
  var token = google.accounts.user.checkLogin(EVENT_FEED_URL);
  if (token) {
    google.accounts.user.logout();
    init();
  } else {
    google.accounts.user.login(EVENT_FEED_URL);
  }
}